gpt4 book ai didi

javascript - 引用对象的属性

转载 作者:行者123 更新时间:2023-11-28 04:37:00 25 4
gpt4 key购买 nike

所以我是这里的初学者,正在尝试根据教程创建一个网络应用程序。根据我所了解到的,在一个对象中,我可以使用代码 this.property-name

来引用该对象的属性

基于下面的代码,只是想确认我的假设,即“this.todos”是通过代码 this.todos.push 创建为下面的对象 ({ 待办事项文本:待办事项文本, 已完成:假, });

因此,我可以在 toDoList 对象中的任何位置引用 this.todos.property-name,例如 this.todos.todoText 和 this.todos.completed?

我不知道我哪里搞砸了。谢谢一群人。

var toDoList = 
{
todos: [],
displayToDo: function()
{
if (this.todos.length ===0)
{
console.log ("your todos is empty")
}
else
{
console.log('My To Dos:');
for (var i=0; i<this.todos.length; i++)
{
if (this.todos[i].completed === true)
{
console.log ('(x)', this.todos[i].todoText);
}
else
{
console.log ('( )', this.todos[i].todoText);
}
}
}
},

addToDo: function(todoText)
{
this.todos.push
({
todoText: todoText,
completed: false,
});
this.displayToDo();
},


changeToDo: function(position, todoText)
{
this.todos[position].todoText = todoText;
this.displayToDo();
},
deleteToDo: function(position)
{
this.todos.splice(position, 1);
this.displayToDo();
},

toggleCompleted: function(position)
{
var todo = this.todos[position];
todo.completed = !todo.completed;
this.displayToDo();
},

toggleAll: function()
{
var totalTodos = this.todos.length;
var completedToDos = 0;


for (var i=0; i<totalTodos; i++)
{
if (this.todos[i].completed === true)
{
completedToDos++;
}
}

if (completedToDos === totalTodos)
{
for (var i=0; i<totalTodos; i++)
{
this.todos[i].completed = false;
}
}
else
{
for (var i=0; i<totalTodos; i++)
{
this.todos[i].completed = true;
}
}
this.displayToDo();
}

};

最佳答案

JavaScript 中没有与 Java 的 getClass() 或 Ruby 的 .class 完全对应的函数。这主要是因为 JavaScript 是一种基于原型(prototype)的语言,而不是 Java 是一种基于类的语言。

根据您需要 getClass() 的用途,JavaScript 中有多种选项:

typeof
instanceof
obj.constructor
func.prototype, proto.isPrototypeOf

一些例子:

function Foo() {}
var foo = new Foo();

typeof Foo; // == "function"
typeof foo; // == "object"

foo instanceof Foo; // == true
foo.constructor.name; // == "Foo"
Foo.name // == "Foo"

Foo.prototype.isPrototypeOf(foo); // == true

Foo.prototype.bar = function (x) {return x+x;};
foo.bar(21); // == 42

应付款:How to get a JavaScript object's class?

关于javascript - 引用对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44118214/

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