[英]How do i rewriting a function code javascript
一個 function returns a new array
,該數組包含 arguments 中具有相同索引的each pair of numbers
的乘積。
var a = [3, 5, 7]; var b = [9, 10, 11]; a.map(function(x, index) { //here x = a[index] //how do i write this as function name(){} console.log(b[index] * x); });
這邊走
var a = [3, 5, 7]; var b = [9, 10, 11]; function myFunction(x,index) { return (b[index] * x); } var c = a.map(myFunction); console.log( c )
var a = [3, 5, 7];
var b = [9, 10, 11];
let c = [];
function name(a, b) {
a.map(function(x, index) {
let result = b[index] * x;
c.push(result);
}
}
name(a, b);
console.log(c) // this will show a new array with the results
您需要從map
回調中返回新值。
var a = [3, 5, 7]; var b = [9, 10, 11]; const res = a.map((x,index)=>b[index] * x); console.log(res);
.map()
的規范說:
map() 方法
creates a new array
,其中填充了在調用數組中的每個元素上調用提供的 function 的結果。
var a = [3, 5, 7]; var b = [9, 10, 11]; function name(value_of_array_a, index_of_array_b) { return b[index_of_array_b] * value_of_array_a; } var result = a.map(name); console.log(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.