如何从同一对象中的另一个键/值创建新键:值对

时间:2022-09-25 08:58:14

I'm pretty new to JavaScript and I've run into an issue on the course I'm taking. I need to create a function that pulls two values from the same object and creates a new key/value. (Is there a better term to use besides key/value by the way?)

我对JavaScript很陌生,而且我在我正在学习的课程中遇到了一个问题。我需要创建一个函数,从同一个对象中提取两个值并创建一个新的键/值。 (顺便说一下除了键/值之外还有更好的术语吗?)

var customers = {
  firstName: "John",
  lastName: "Doe"
};

function createFullName(object) {
}

Im trying to make the function create a new key/value that is a string of the full name.

我试图让函数创建一个新的键/值,它是一个全名的字符串。

I've tried a for...in loop but I'm not sure how to get each iteration of the properties add to just one value. I can only do this sort of thing with an array.

我已经尝试了for ... in循环,但我不确定如何将每个属性的迭代添加到一个值。我只能用数组做这种事情。

Hope that made sense.

希望有道理。

Thanks!

1 个解决方案

#1


1  

To create the new key/value pair, just define it using the dot notation:

要创建新的键/值对,只需使用点表示法定义它:

var customers = { firstName: "John", lastName: "Doe" };

function createFullName(object) {
    object.fullName = object.firstName + " " + object.lastName;
}

createFullName(customers);

console.log(customers)

If you don't have a valid JavaScript identifier for the property (here I'm using fullName, which is) use a bracket notation instead.

如果您没有该属性的有效JavaScript标识符(这里我使用的是fullName),请使用括号表示法。

#1


1  

To create the new key/value pair, just define it using the dot notation:

要创建新的键/值对,只需使用点表示法定义它:

var customers = { firstName: "John", lastName: "Doe" };

function createFullName(object) {
    object.fullName = object.firstName + " " + object.lastName;
}

createFullName(customers);

console.log(customers)

If you don't have a valid JavaScript identifier for the property (here I'm using fullName, which is) use a bracket notation instead.

如果您没有该属性的有效JavaScript标识符(这里我使用的是fullName),请使用括号表示法。