javascript推送返回数字而不是对象 [英] javascript push returning number instead of object
问题描述
我确定这只是我所缺少的一个简单而愚蠢的错误,但是有人可以告诉我为什么返回3
而不是[{ "method": 'popup', "minutes": ''}, {"method": 'email', "minutes": '10'}, {"method": 'popup', "minutes": '20'}];
吗?
I'm sure this is just some simple silly mistake that I'm missing, but can anyone tell me why 3
is being returned instead of [{ "method": 'popup', "minutes": ''}, {"method": 'email', "minutes": '10'}, {"method": 'popup', "minutes": '20'}];
?
我制作了一个jsfiddle,因此您也可以看到: https://jsfiddle.net/qk10arb0/3/
I made a jsfiddle so you can see as well: https://jsfiddle.net/qk10arb0/3/
HTML
<p>Click the button to add a new element to the array.</p>
<button onclick="addNewReminder()">Try it</button>
<p id="demo"></p>
JavaScript
function addNewReminder(){
var newReminder = {
"method": 'popup',
"minutes": '20'
};
var reminders = [{
"method": 'popup',
"minutes": ''
}, {
"method": 'email',
"minutes": '10'
}];
reminders = reminders.push(newReminder);
document.getElementById("demo").innerHTML = reminders;
}
谢谢!
推荐答案
Array#push
方法在原位运行,您不必将其分配给新变量.它不会返回新数组,但会修改原始数组并返回length
.这就是为什么您得到3
作为结果的原因.
Array#push
method works in situ, you don't have to assign it to a new variable. It won't return a new array, but will modify the original one and will return it's length
. That's why you are getting 3
as the result.
要获得所需的结果,只需调用它,而不分配任何变量:
To get the desired result, just call it, without assigning to any variable:
reminders.push(newReminder);
这篇关于javascript推送返回数字而不是对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!