js语法练习
js中两种for循环语句的区别
以钞票这题为例
传送门https://www.acwing.com/problem/content/description/655/
for p of money:
1.遍历数组, p拿到的是数组对象的值
let buf = “”;
process.stdin.on(“readable”, function(){
let chunk = process.stdin.read();
if(chunk) buf += chunk.toString();
})
process.stdin.on(“end”, function(){
let n = parseInt(buf);
console.log(n);
let money = [100, 50, 20, 10, 5, 2, 1];
for(p of money){
let cnt = parseInt(n / p);
console.log(${cnt} nota(s) de R$ ${p},00
);
n %= p;
}
})
for p in money:
2.遍历数组, p拿到的是数组对象的下标
let buf = “”;
process.stdin.on(“readable”, function(){
let chunk = process.stdin.read();
if(chunk) buf += chunk.toString();
})
process.stdin.on(“end”, function(){
let n = parseInt(buf);
console.log(n);
let money = [100, 50, 20, 10, 5, 2, 1];
for (p in money){
let cnt = parseInt(n / money[p]);
console.log(${cnt} nota(s) de R$ ${money[p]},00
);
n %= money[p];
}
})
遍历对象, for in 拿到的是对象的属性名, 而for of会报错,如图