什么是 JavaScript 对象和属性? [英] What are JavaScript Objects and Properties?

查看:47
本文介绍了什么是 JavaScript 对象和属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以用外行的术语在 Javascript 中向我解释对象和属性吗?Javascript MDN 文档让我很困惑.

Can anyone explain objects and properties to me in Javascript in layman's terms? The Javascript MDN documentation is confusing me.

我正在尝试解决关于对象和属性的 Javascript 教程中的问题问题如下,我对代码的尝试,我想我尽可能地遵循了 MDN.任何帮助将不胜感激!

I am trying to solve a problem in a Javascript tutorial about objects and properties The question is below and my attempt at the code, I think I followed the MDN as far as I can grasp it. Any help would be appreciated!

问题:将属性参数的值添加为对象参数的键.新属性的值应设置为 null.添加新属性后返回对象.

Question: Add the value of the property argument as a key on the object argument. The value of the new property should be set to null. Return object after adding the new property.

输入示例:

{}, 'hello'
{ x: 5 }, 'y'

输出示例:

{ hello: null }
{ x: 5, y: null }

注意:属性名称不是属性".名称是名为 property(字符串)的参数的值.

note: the property name is NOT 'property'. The name is the value of the argument called property (a string).

我的代码://注意:函数 addProperty(object, property) 已经在控制台中,我必须在其中编写解决方案.

My code: //NOTE: the function addProperty(object, property) was already in the console and I have to write the solution inside of it.

function addProperty(object, property) {
  // code here
  let result = addProperty({x: 5}, 'y');
  obj[property] = null;
  return obj;
}

addProperty(x, 'y'); 

推荐答案

外行的解释:

对象是属性的集合.您可以为对象命名以保持井井有条.例如,让我们创建一个 person 对象.

An object is a collection of properties. You can give a name to the object to keep things organized. For example, lets create a person object.

var person = {};

该对象目前没有任何属性.为了进一步描述人,我们可以向对象添加属性.

The object has no properties right now. To further describe the person we can add properties to the object.

person.Name = 'Zim';
person.Age = 29;
person.Gender = 'Male';
person.Weight = 80;

现在这个对象有一些属性来帮助描述它.写同一件事的不同方式:

Now this object has some properties to help describe it. A different way to write the same thing:

var person = { Name: 'Zim', Age: 29, Gender: 'Male', Weight: 80 };

如果我们必须创建一个显示人员列表的程序,将我们所有的信息存储在对象中将有助于使事情井井有条.

If we had to create a program that displays a list of people, storing all of our information inside objects would help keep things organized.

对象属性有时称为键.

向对象添加属性:

您可以使用方括号向对象添加属性,就像您在 addProperty 函数中所做的那样.如果你只是需要它来添加一个属性,将该属性设置为 null 并返回它看起来像这样的结果:

You can add a property to an object using brackets, just like you had in your addProperty function. If you just need it to add a property, set that property to null and return the result it would look something like this:

function addProperty(object, property) {
  // code here
  object[property] = null;
  return object;
}

这将让我们通过调用

addProperty(person, 'Occupation');
addProperty(person, 'Income');
addProperty(person, 'Height');

这篇关于什么是 JavaScript 对象和属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆