避免 .slice 不是函数(javascript)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26841221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:35:29  来源:igfitidea点击:

avoid .slice is not a function (javascript)

javascript

提问by Bogdan M.

so i have a variable which as this point has a static definition, i want it to get now the value dynamically from an if-elsestatement but the above mentioned error pops out:

所以我有一个变量,因为这一点有一个静态定义,我希望它现在从一个if-else语句动态获取值,但上面提到的错误弹出:

var x = [{a:b},{c:d},{e:f}]

and i want to change it to get the value from a function:

我想更改它以从函数中获取值:

var x = function(){
    if(true){
      return [{a:b},{c:d},{e:f}]
    }else{
      return [{f:g},{h:i}]
    }
}

But I get an error x.slice is not a functionCan what am i doing wrong? Looked around but cant manage to fix this... isn't it possible?

但是我得到一个错误x.slice is not a function我做错了什么?环顾四周,但无法解决这个问题……这不可能吗?

回答by Joe

xis a function, so you're trying to call .slice()on a function. You want to call x()and use the return value, then slice that:

x是一个函数,所以你试图调用.slice()一个函数。您想调用x()并使用返回值,然后将其切片:

x().slice(1);

回答by DARK_DUCK

x is a function so it does not have slice you should run it before

x 是一个函数,所以它没有切片,你应该先运行它

var x = (function(){
    if(true){
      return [{a:b},{c:d},{e:f}]
    }else{
      return [{f:g},{h:i}]
    }
})()