[英]Can't access property if object is taken from array
This outputs "value", while with the commented out line it is "undefined". 输出“值”,带注释的行则为“未定义”。 Why is that? 这是为什么?
<!DOCTYPE html>
<html>
<body>
<script>
function Obj(property) {
this.property = property;
}
var arr = [new Obj("value")]
var obj = new Obj("value");
//var obj = arr.splice(0, 1);
console.log(obj.property);
</script>
</body>
</html>
That's because splice()
returns an array of elements: 这是因为splice()
返回一个元素数组:
console.log(obj[0].property);
As per the documentation (I've bolded the significant part that pertains to your example) : 根据文档 (我已经将与您的示例有关的重要部分加粗了) :
An array containing the deleted elements. 包含已删除元素的数组。 If only one element is removed, an array of one element is returned . 如果仅删除一个元素,则返回一个元素的数组 。 If no elements are removed, an empty array is returned. 如果没有删除任何元素,则返回一个空数组。
function Obj(property) {
this.property = property;
}
var arr = [new Obj("value")]
var obj = arr.splice(0, 1);
console.log(obj[0].property);
// "value"
this is because splice returns extracted array based on the parameters given, so obj becomes an array containing an element. 这是因为splice根据给定的参数返回提取的数组,所以obj成为包含元素的数组。 so you must use console.log(obj[0].property); 因此,您必须使用console.log(obj [0] .property);
splice()
function returns an array with spliced items . splice()
函数返回带有已拼接项的数组。 so access the property you should do: 因此,请访问该属性:
var obj = arr.splice(0, 1)[0]; // extract the object first
console.log(obj.property);
OR 要么
var obj = arr.splice(0, 1);
console.log(obj[0].property);
OR 要么
var obj = arr[0];
console.log(obj.property);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.