简体   繁体   English

如何在Javascript中分配具有相同属性的多个对象

[英]How to assign numerous objects with identical properties in Javascript

How do you create numerous objects under the same method with identical properties in Javascript? 如何用相同的方法在Javascript中使用具有相同属性的多个对象?

Im familiar with how to create objects in Javascript as such: 我不熟悉如何使用Javascript这样创建对象:

var myCar = new Object(); 
myCar.make = 'ford';
myCar.model = 'mustang';
myCar.year = 1969;

But what if I wanted to assign an array to an object and have all the values have the same properties? 但是,如果我想为对象分配数组并让所有值具有相同的属性怎么办?

Arr = [1,2];
Arr[i].value === Arr[i]
Arr[j].value === Arr[j]
Arr[i].value === Arr[j].value
!Arr[i].hasOwnProperty('value')
!Arr[j].hasOwnProperty('value')

where as the value method is the same and not unique to the object 其中值方法是相同的,并且不是对象唯一的

object1.hasOwnProperty('value'); //Evaluates to `false`

I'm used to programming in Python so my first guess is to create a dictionary and dynamically assign the array to the values but I'm not sure how to work with properties in Javascript objects. 我习惯于使用Python进行编程,因此我的第一个猜测是创建一个字典并将该数组动态分配给这些values但是我不确定如何使用Javascript对象中的properties

Edit: Mistakenly included '==' operators when I meant to use '===' operators. 编辑:当我打算使用'==='运算符时,错误地包括了'=='运算符。

You need to do it like this - by creating an object. 您需要这样做-通过创建一个对象。 Also use the assignment operator = not comparison operator == : 也可以使用赋值运算符=而不是比较运算符==

 let Arr = [1,2]; let i = 0; let j = 1; Arr[i] = { value: Arr[i] }; Arr[j] = { value: Arr[j] }; console.log(Arr); 
 .as-console-wrapper { max-height: 100% !important; top: auto; } 

I don't know if this is what you're asking for but you can create your own objects in two ways 我不知道这是否是您要的,但是您可以通过两种方式创建自己的对象

function Car (make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
}

// you can also add methods using the object's protoype
Car.prototype.isNissan() {
    return this.make == 'Nissan';
}

In modern syntax you can create classes 使用现代语法,您可以创建类

class Car {
    constructor(make, model, year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }

    methodName() {
        // method body
    }
}

And use it in your code like so 像这样在你的代码中使用它

let myCar = new Car('Nissan', 'some model', 2018);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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