将数据压入对象清除其他值

Pushing data into object clears the other values

本文关键字:清除 其他 对象 数据      更新时间:2023-09-26

我正在尝试将数据推送到对象中,但是一旦我将数据推送到userID.name, userID.age的值就会在控制台上重置(?)。下面是我的代码:

if (input.indexOf("ben") >= 0){
    var slot = splitInput.indexOf("ben");
    console.log(slot)
    i = slot + 1;
    if (splitInput[i].indexOf(0) >= 0 || splitInput[i].indexOf(1) >= 0 || splitInput[i].indexOf(3) >= 0 || splitInput[i].indexOf(4) >= 0 || splitInput[i].indexOf(4) >= 0 || splitInput[i].indexOf(5) >= 0 || splitInput[i].indexOf(6) >= 0 || splitInput[i].indexOf(7) >= 0 || splitInput[i].indexOf(8) >= 0 || splitInput[i].indexOf(9) >= 0){
        i = 0;
        var slot = splitInput.indexOf("ben");
        // console.log(slot)
        i = slot + 1;
        userID.age = splitInput[i];
        console.log(userID);
    } if (splitInput[i].indexOf("a") >= 0 || splitInput[i].indexOf("e") >= 0 || splitInput[i].indexOf("i") >= 0 || splitInput[i].indexOf("u") >= 0){
        i = 0;
        var slot = splitInput.indexOf("ben");
        // console.log(slot)
        i = slot + 1;
        userID.name = splitInput[i];
        console.log(userID);
    }
}

这是我的splitInput:

var splitInput = input.split(" ");

输入通过getElementById函数收集。

当我手动记录userID时,我得到这个错误VM935:1 Uncaught ReferenceError: userID is not defined(…),这可能与它有关,尽管console.log(userID)工作得很好。

如果您需要更多信息,请告诉我。

提前感谢!

在赋值给对象属性之前,如UserID.age,必须首先定义UserID本身。

所以在你访问UserID的属性之前放这个:

var userID = {};

代码注释

你检查数字和带元音的单词的方式不是很好。它有很多重复的代码。同样在if块内,您再次搜索单词"ben",而您已经完成了……似乎没有必要再做一次。

看看这个版本的代码:

// Sample data
var input = 'ik ben 51 jaar';
var splitInput = input.split(" ");
// This was missing:
var userID = {};
// Move retrieval of slot before the `if` so it can be reused
var slot = splitInput.indexOf("ben");
if (slot >= 0){
    console.log('slot:', slot);
    i = slot + 1;
    // Make sure you are not at the end of the array, and 
    // use a regular expression to see next word consists of digits only
    if (i < splitInput.length && splitInput[i].match(/^'d+$/)){
        // convert the word to number with unitary plus:
        userID.age = +splitInput[i];
    } 
    // You'll maybe want to do an else here.
    // Use regular expression again; don't forget the "o"
    else if (i < splitInput.length && splitInput[i].match(/a|e|i|o|u/)){
        userID.name = splitInput[i];
    }
    console.log(userID);
}