从函数给定的数组中获取值

时间:2019-05-09 17:43:56

标签: javascript

我正在尝试从数组中打印单个值,但它似乎不起作用(获取未定义)。当我打印出数组本身时,它表明值包含在数组中的索引0和1处。

let imgDim = getMeta(url);
let width = imgDim[0];
let height = imgDim[1];
let testString = "s994320";
if (/^[ms]\d+$/.test(testString) == true) {
  console.log(imgDim); //works
  console.log(width, height); //undefined undefined
}

function getMeta(url) {
let array = [];
var img = new Image();
img.src = url;
img.addEventListener("load", function () {
    array.push(this.naturalWidth);
    array.push(this.naturalHeight);
});
return array;

}

这里的区别是我从外部函数返回一个数组,该函数通过addEventListener接收值。只是停留在为什么我可以打印结果本身而不是数组中一次实际数据的原因。

0 个答案:

没有答案
相关问题