js对象用输入

时间:2017-02-07 07:36:11

标签: javascript

我想在js对象中存储或保存数据,如下所示:

var car= {};
car[number] = user_input;   

...给予

car = {1:"Fiat"}; 

但我只想要最多三个值。

car = {1:"Fiat", 2:"Honda"};// two values
car = {1:"Fiat", 2:"Honda", 3:"Ford"}; //three values

所以,如果在添加了三个值之后还有另一个输入,那么我想要它以便它将替换第一个值,如下所示:

car = {1:"Nissan", 2:"Honda", 3:"Ford"};

然后第二个值将被替换,依此类推:

car = {1:"Nissan", 2:"Tesla", 3:"Ford"};

设计这个的优雅方式是什么?

任何建议都将不胜感激。

修改

为了澄清问题,密钥是id号,例如“234”或“5432”或“2342”。

例如:

car = {1233:"Nissan", 555:"Tesla", 3345:"Ford"};    

3 个答案:

答案 0 :(得分:2)

如果您的号码会将其值更改为1,则可以在该媒体资源中使用remainder operatornumber % 3

number % 3 - 这会使您的索引从0升级到2。因此,如果您输入4th元素,如果您从4 % 3 === 1开始,则其索引将为1

var car= {};
car[number % 3] = user_input; 

示例

var car= [];
var number = 0;
var input;

while(number < 10){
  input = prompt();
  car[number % 3] = input;
  console.log(car);
  number++;
}

使用ID,您可以存储它们并使用number来获取相应的ID。

var ids = [234, 4641, 1352];

var car= {};
var number = 0;
var input;
var ids = [234, 4641, 1352];

while(number < 10){
  input = prompt();
  car[ids[number % 3]] = input;
  console.log(car);
  number++;
}

答案 1 :(得分:2)

您可以使用remainder operator %并将值移至范围内。然后为基于一个的间隔添加一个。

var car = {},
    insertCar = function (index) {
        return function (carName) {
            car[index + 1] = carName;
            index++;
            index %= 3;
        }
    }(0);


insertCar('Fiat');
console.log(car);
insertCar('Honda');
console.log(car);
insertCar('Ford');
console.log(car);
insertCar('Nissan');
console.log(car);
insertCar('Tesla');
console.log(car);
.as-console-wrapper { max-height: 100% !important; top: 0; }

使用给定键[234, 4641, 1352]和循环

var car = {},
    insertCar = function (index) {
        var keys = [234, 4641, 1352];
        return function (carName) {
            car[keys[index]] = carName;
            index++;
            index %= keys.length;
        }
    }(0);


insertCar('Fiat');
console.log(car);
insertCar('Honda');
console.log(car);
insertCar('Ford');
console.log(car);
insertCar('Nissan');
console.log(car);
insertCar('Tesla');
console.log(car);
.as-console-wrapper { max-height: 100% !important; top: 0; }

使用数组,如建议

var car = [],
    insertCar = function (index) {
        return function (carName) {
            car[index] = carName;
            index++;
            index %= 3;
        }
    }(0);


insertCar('Fiat');
console.log(car);
insertCar('Honda');
console.log(car);
insertCar('Ford');
console.log(car);
insertCar('Nissan');
console.log(car);
insertCar('Tesla');
console.log(car);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

您可以使用以下内容:

var carCount = "Take this as UserInput";
var newValue = "Take the value as Input as well"

if (carCount < 3){
  (car[carCount] = newValue);
}