JavaScript 拼接问题
A 有一个对象数组,我想从中删除第一个元素并读取它的一些属性。但我不能。这是代码:
$.test = function(){
var array = [
{a: "a1", b: "b1"},
{a: "a2", b: "b2"},
{a: "a3", b: "b3"}
];
alert("0. element's 'a': " + array[0].a);
alert("length: " + array.length);
var element = array.splice(0, 1);
alert("length: " + array.length);
alert("removed element's 'a': " + element.a);
}
我得到:
3
a1
2
undefined
为什么我总是得到“未定义”? splice 方法应该删除定义的元素并返回它/它们。
A have an array of Objects and I'd like to remove the first element from it and read some of its properties. But I can't. Here is the code:
$.test = function(){
var array = [
{a: "a1", b: "b1"},
{a: "a2", b: "b2"},
{a: "a3", b: "b3"}
];
alert("0. element's 'a': " + array[0].a);
alert("length: " + array.length);
var element = array.splice(0, 1);
alert("length: " + array.length);
alert("removed element's 'a': " + element.a);
}
I get:
3
a1
2
undefined
Why do I always get "undefined"? The splice method is supposed to remove the defined element(s) and return it / them.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
shift
来完成此操作 - 它删除并返回数组中的第一个元素。您的问题是 splice 返回一个数组,因此您的代码必须是:
You can use
shift
to accomplish this - it removes and returns the first element in an array.Your problem is that splice returns an array so your code would have to be:
splice
返回已删除元素的数组。这应该有效
splice
returns a array of the removed elements.this should work