Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在javascript中向对象的方法添加项_Javascript_Arrays_Object - Fatal编程技术网

如何在javascript中向对象的方法添加项

如何在javascript中向对象的方法添加项,javascript,arrays,object,Javascript,Arrays,Object,我想在items数组中添加bar 尝试这样做: myObj.item().push('bar') 但当我执行console.logmyObj.item时,我会返回['foo'] 这种行为有什么原因吗 let myObj = { item: _ => ['foo'] // you make a new function called item that ALWAYS returns an array called foo } push'bar'实际上将bar推送到函数myObj

我想在items数组中添加bar

尝试这样做:

myObj.item().push('bar')
但当我执行console.logmyObj.item时,我会返回['foo'] 这种行为有什么原因吗

let myObj = {  
   item: _ => ['foo'] // you make a new function called item that ALWAYS returns an array called foo
}
push'bar'实际上将bar推送到函数myObj.item返回的数组中。但这并没有持续下去。下次调用myObj.item时,仍然会得到['foo'],因为这是函数返回的结果

如果您想直接推送到item数组,可以创建一个初始值为['foo']的数组,如下所示

let myObj = {  
   item: ['foo'] 
}

然后你可以做myObj.item.push'bar'

您的方法没有被更新,而是将“bar”压入方法返回的数组中,您可以用这种方式对返回的数组进行控制台日志记录

        let myObj = {
            item: _ => ['foo']
        }

        let arrayInAir = myObj.item();
        arrayInAir.push('bar');
        console.log(arrayInAir);
在item方法返回内容之前,您可以决定它将返回什么

        let myObj = {
            what: ['foo'],
            item: _ => myObj.what
        }
        myObj.what.push('bar');

        console.log(myObj.item());

是的,这就是它的工作原理。每次调用函数时,它都返回['foo']。因为您是这样实现的。如果您想要一个数组,那么只需编写let myObj={item:['foo']},不需要方法将数组添加为属性。使用item:['foo']而不是item:['foo']的原因是什么?你好像有XY问题。
        let myObj = {
            what: ['foo'],
            item: _ => myObj.what
        }
        myObj.what.push('bar');

        console.log(myObj.item());