简体   繁体   中英

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:

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.

Working Example

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. so you must use console.log(obj[0].property);

splice() function returns an array with spliced items . 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM