1 回答
TA贡献1824条经验 获得超6个赞
方案一(直接修改原图):
function task09(pre_map, arr) {
function isArmstrong(num) {
if (num < 0) return false;
const numToStr = num.toString();
let sum = 0;
for (let i = 0; i < numToStr.length; i++) {
sum += Math.pow(parseInt(numToStr[i]), 3);
}
return num === sum;
}
arr.forEach(item => {
if (pre_map.has(item)) {
pre_map.delete(item);
} else {
pre_map.set(item, isArmstrong(item));
}
});
return pre_map;
}
/********
* test *
********/
const myMap = new Map();
myMap.set(0, true);
myMap.set(1, true);
myMap.set(10, false);
myMap.set(19, false);
myMap.set(370, true);
const myArr = [10, 407];
console.log('myArr:', myArr);
console.log('myMap (before):');
for (let item of myMap) {
console.log(item);
}
task09(myMap, myArr);
console.log('myMap (after):');
for (let item of myMap) {
console.log(item);
}
解决方案2(原图不做修改):
function task09(pre_map, arr) {
const post_map = new Map(pre_map);
function isArmstrong(num) {
if (num < 0) return false;
const numToStr = num.toString();
let sum = 0;
for (let i = 0; i < numToStr.length; i++) {
sum += Math.pow(parseInt(numToStr[i]), 3);
}
return num === sum;
}
arr.forEach(item => {
if (post_map.has(item)) {
post_map.delete(item);
} else {
post_map.set(item, isArmstrong(item));
}
});
return post_map;
}
/********
* test *
********/
const myMap = new Map();
myMap.set(0, true);
myMap.set(1, true);
myMap.set(10, false);
myMap.set(19, false);
myMap.set(370, true);
const myArr = [10, 407];
const myUpdatedMap = task09(myMap, myArr);
console.log('myArr:', myArr);
console.log('myMap:');
for (let item of myMap) {
console.log(item);
}
console.log('myUpdatedMap:');
for (let item of myUpdatedMap) {
console.log(item);
}
添加回答
举报