Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Javascript数组中使用运算符_Javascript_Arrays - Fatal编程技术网

在Javascript数组中使用运算符

在Javascript数组中使用运算符,javascript,arrays,Javascript,Arrays,我需要向数组中的一些值添加变量。简单地说,我想这样做: var a = prompt("Enter either PNG or JPG"); var array = ["foo." + a, "bar." + a,"vid.oog"]; var x = prompt("Which image to display?"); document.getElementById('imge').src=array[x] 它不让我;它只是返回undefined,有什么办法吗?我不想定义一堆变量,然后将这

我需要向数组中的一些值添加变量。简单地说,我想这样做:

var a = prompt("Enter either PNG or JPG");
var array = ["foo." + a, "bar." + a,"vid.oog"];

var x = prompt("Which image to display?");
document.getElementById('imge').src=array[x]
它不让我;它只是返回undefined,有什么办法吗?我不想定义一堆变量,然后将这些变量粘贴到数组中。我也不能简单地将+a添加到最后一行的末尾,因为这将导致数组中的第三个元素为vid.oogjpg或vid.oogpng


我知道用Python你可以做到这一点。遗憾的是,不是JS。

只需如下声明您的数组:

var array = ["foo","bar","vid.oog"]; // leave them without extension it will be added later.
然后你可以这样做:

array.map(function(x){
  return  x.indexOf('.') == -1 ? x + "." + a : x; 
});

为什么不先创建元素,然后将它们添加到数组中?应该按原样工作-例如:如果您解释一下,那就太好了。@user3138189,它检查每个项目,然后检查它是否包含扩展名,否则它会将用户提供的扩展名添加到其中。