gpt4 book ai didi

javascript - 从前一个函数添加到数组

转载 作者:行者123 更新时间:2023-11-28 13:21:34 24 4
gpt4 key购买 nike

所以我想访问我在上一个函数中创建的数组。然后在 id1,id2,id3 中,我想创建一个新属性并为该属性赋予一个值。我以为我知道我应该做什么,但我所做的却不起作用。我收到错误 IdArray 未定义。

HTML:

        <p id="show_me"></p>
<button onclick="ObjectArray()">click me</button>
<p id="added"></p>
<button onclick="Added()">Add</button>

javascript 上一个函数:

var ObjectArray = function() {
// object literal
var id1 = {
firstName: "John",
lastName: "Doe",
id: "12345"
};

// keyword new
var id2 = new Object;
id2.firstName = "Adam";
id2.lastName = "Bakely";
id2.id = "abcdef";

// object constructor
function employee(first, last, id) {
this.firstName = first;
this.lastName = last;
this.id = id;
}
var id3 = new employee("Dallas", "Star", "abc123");

//create an array
var IdArray = [id1, id2, id3];
}

JavaScript 新功能:

function Added(IdArray, sex){
IdArray.push({sex : sex})
IdArray[0].sex = "male";
document.getElementById("added").innerHTML = IdArray[0];
}

我迷路了,那么如何从上一个函数访问数组并添加到其中?

最佳答案

您无权访问其他函数中的变量,但是您可以访问函数上方声明的变量。你真正的问题是无法理解构造函数,这对你将来会大有裨益。看看这个:

function Employee(id, firstName, lastName, middleName){
this.id = id; this.firstName = firstName; this.lastName = lastName;
this.middleName = middleName;
this.notes = [];
this.getFullName = function(){
var mn = this.middleName ? ' '+this.middleName : '';
return this.firstName+mn+' '+this.lastName;
}
this.createNote = function(note){
this.notes.push(note);
return this;
}
this.getNotesString = function(delimiter){
return this.notes.join(delimiter);
}
}
var employee1 = new Employee('abc123', 'Joe', 'Schmoe');
employee1.createNote('Note You Want to Store.');
employee1.createNote('Just Another Test Note.');
var employee2 = new Employee('def456', employee1.firstName, 'Smith', 'Walter'); // notice how you access the other instance firstName
console.log(employee1.getFullName());
console.log(employee1.getNotesString('|'));
console.log(employee2.getFullName());
console.log(employee2.createNote('Note 1').createNote('Note 2').createNote('Note 3').getNotesString('|')); // by returning `this` you can access other methods in the same Constructor

关于javascript - 从前一个函数添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32544375/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com