将数据压入对象清除其他值
Pushing data into object clears the other values
我正在尝试将数据推送到对象中,但是一旦我将数据推送到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);
}
相关文章:
- 如何添加浮动和非浮动,其他
- 与其他库的jQuery.noConflict()
- 播放当前视频时如何停止其他视频?JavaScript
- 清除文本区域会中断其他JS函数
- 如何使用javascript或其他方法清除IE DNS缓存
- 如何在单击任何其他控件时清除文本
- 在选择任何其他单选按钮时清除文本框
- 如何清除复选框当选中其他复选框时?使用java脚本
- 可以't从其他函数中清除函数中调用的inverval
- 设置并清除'点击'事件功能,不清除其他事件
- 有没有一种方法可以从画布上清除一个元素而不消除其他元素?
- 切换融合表层:如何在选中新复选框时清除所有其他复选框
- 清除其他文本并在主选择更改时选择字段值
- 如何从其他视图中清除一个视图的输入值
- 清除基于其他选择菜单的选择菜单
- 将数据压入对象清除其他值
- 如何在不影响php中任何其他函数的情况下清除先前返回的结果?
- 清除间隔不起作用(尝试了所有其他答案)
- 动态生成select清除javascript中的其他元素
- 弹出框中的引导日期选择器在触发事件显示时清除其他输入