假设我有诸如;
之类的对象var obj = {
name: "alex",
surname: "black",
age: 21,
grade: 14
}
我想将所有值无效为;
var obj = {
name: "",
surname: "",
age: 0,
grade: 0
}
我该怎么做?我可以通过Object.keys(obj)
浏览键,并根据其类型将每个键无效。
喜欢;
var str ="";
for(var i =0; i < obj.length; i++){
if(type of obj[i] === "string")
str += Object.keys(obj)[i] + ': "",n';
if(type of obj[i] === "integer")
str += Object.keys(obj)[i] + ': 0,n';
}
是正确的方法吗?
编辑:谢谢您的所有答案。但是此对象也可以包含对象。因此,我应该循环浏览所有键,并作为您的示例显示。我是对的吗?
使用 for..in
循环迭代对象属性:
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
obj[prop] = { string: '', number: 0 }[typeof obj[prop]];
}
}
或者也许是循环内的switch
:
switch (typeof obj[prop]) {
case 'string':
obj[prop] = '';
break;
case 'number':
obj[prop] = 0;
break;
default:
obj[prop] = null;
}
Object.keys(obj).forEach(function(key) {
console.log(key, obj[key]);
if(type of obj[key] === "string")
// do something
if(type of obj[key] === "integer")
// do something
});
都喜欢其中的任何一个:
for/in (用于迭代对象的所有属性)或
object.keys( obj )。> var obj = {
name: "alex",
surname: "black",
age: 21,
grade: 14,
someObject: {dob: "12/16/66", address: "10 Main Street"}
}
var obj2 = {
name: "alex",
surname: "black",
age: 21,
grade: 14,
someObject: {dob: "12/16/66", address: "10 Main Street"}
}
// Using for/in
function reset(obj){
for(var k in obj){
switch(typeof obj[k]){
case "string":
obj[k]="";
break;
case "number":
obj[k]= 0;
break;
case "boolean":
obj[k]= false;
break;
case "object":
obj[k]= null;
break;
}
}
}
// Using Object.keys()
function reset2(obj){
Object.keys(obj).forEach(function(k){
switch(typeof obj2[k]){
case "string":
obj[k]="";
break;
case "number":
obj[k]= 0;
break;
case "boolean":
obj[k]= false;
break;
case "object":
obj[k]= null;
break;
}
});
}
reset(obj);
console.log(obj);
reset2(obj2);
console.log(obj2);