我想将bar
添加到items
数组中。
let myObj = {
item:_ => ['foo']
}
尝试这样做:
myObj.item().push('bar')
但是当我做console.log(myObj.item())
的时候,我得到了['foo']
,有什么原因导致这种行为吗?
发布于 2018-07-27 19:04:31
let myObj = {
item: _ => ['foo'] // you make a new function called item that ALWAYS returns an array called foo
}
myObj.item().push('bar')
实际上将bar推送到函数myObj.item()
返回的数组中。但这并不是持久的。下次调用myObj.item()
时,您仍然会得到'foo‘,因为这是函数返回的内容。
如果您想要直接推送到item数组,请将item创建为具有初始值'foo‘的数组,如下所示。
let myObj = {
item: ['foo']
}
然后就可以执行myObj.item.push('bar');
了
发布于 2018-07-27 19:43:46
您的方法没有被更新,而是将'bar‘推入由您的方法返回的数组中,您可以通过这种方式控制日志记录该返回的数组。
let myObj = {
item: _ => ['foo']
}
let arrayInAir = myObj.item();
arrayInAir.push('bar');
console.log(arrayInAir);
在item方法返回something.So之前,您可以决定它将返回什么(evaluate to)。
let myObj = {
what: ['foo'],
item: _ => myObj.what
}
myObj.what.push('bar');
console.log(myObj.item());
https://stackoverflow.com/questions/51556546
复制相似问题