process.stdin.on("end", function(){ let n = parseFloat(buf); if(n >= 0 && n <= 25) console.log(`Intervalo [0,25]`); elseif(n > 25 && n <= 50) console.log(`Intervalo (25,50]`); elseif(n > 50 && n <= 75) console.log(`Intervalo (50,75]`); elseif(n > 75 && n <= 100)console.log(`Intervalo (75,100]`); elseconsole.log(`Fora de intervalo`); });
循环语句
JavaScript中的循环语句与C++中类似,也包含for、while、do while循环。
枚举对象或数组时可以使用:
for-in循环,可以枚举数组中的下标,以及对象中的key。
for-of循环,可以枚举数组中的值,以及对象中的value。
统计正数的个数
1 2 3 4 5 6 7 8 9 10 11 12 13 14
let buf = "" process.stdin.on("readable", function(){ let chunk = process.stdin.read(); if(chunk) buf += chunk.toString(); });
process.stdin.on("end", function(){ let v = buf.split('\n').map(x => {returnparseFloat(x);}); let cnt = 0; for(let x of v){ if(x > 0)cnt++; } console.log(`${cnt} positive numbers`); });
process.stdin.on("end", function(){ let dx = [-1, 0, 1, 0], dy = [0, 1, 0, -1]; let [n, m] = buf.split(' ').map(x => {returnparseInt(x);}); let g = []; for(let i = 0; i < n; i++){ let gv = []; for(let j = 0; j < m; j++){ gv.push(0); } g.push(gv); } let d = 1, x = 0, y = 0, cur = 1; for(let i = 1; i <= n * m; i++){ g[x][y] = i; let nx = dx[d] + x, ny = dy[d] + y; if(nx < 0 || ny < 0 || nx >= n || ny >= m || g[nx][ny] !== 0){ d = (d + 1) % 4; nx = dx[d] + x; ny = dy[d] + y; } x = nx, y = ny; } for(let i = 0; i < n; i++){ let s = ""; for(let j = 0; j < m; j++){ s += g[i][j].toString(); s += ' '; } console.log(s); } });
对象
c++中map相类似,但是其中的value可以变量、数组、对象、函数等,与数组的类似。
1 2 3 4 5 6 7 8
let person = { name: "xxxx", age: 18, money: 0, add_money: function (x) { this.money += x; } }