Javascript 和 jQuery 数组未定义

Javascript and jQuery arrays undefined

我试图设置一个数组,但是当我使用 console.log(array_name) 时,它会打印计数器 (x) 的数字,而不是打印图像的路径。 一旦我尝试使用 console.log(img[x]) 检查变量的内容是否是图像的来源,未定义就会出现。 但由于 img 也不起作用,我不知道发生了什么。

$(window).on('load', function(){
    var x = 0;
    var img = [];
        $(".gallery_img").each(function(img){
            var image = new Image();
            image.src = $(this).attr("src");
            x = x + 1;
            img[x] = image.src;
            console.log(img);
            console.log($(this).attr("src"));

我是 jquery 和 javascript 的新手,所以我非常感谢一些具体的解释,而不仅仅是解决方案。我希望我已经足够具体,而不是重复

尝试将数组变量 var img = []; 重命名为 var imgs = [];

因为您在此处的函数中使用了相同的变量:

$(".gallery_img").each(function(img)..

根据@guest271314 的评论添加。

之所以打印计数而不是路径,是因为 .each(index, element) 中的第一个参数是元素集合中元素的索引

在数组有机会将图像添加到索引 0 之前,您正在递增数组。

$(window).on('load', function(){
var x = 0;
var img = [];
    $(".gallery_img").each(function(img){
        var image = new Image();
        image.src = $(this).attr("src");
        x = x + 1; //<- x becomes 1
        img[x] = image.src; //<- img[0] is undefined as img[1] is where the index began.
        console.log(img);
        console.log($(this).attr("src"));

尝试将您的代码更改为此。

 $(window).on('load', function(){
var x = 0;
var img = [];
    $(".gallery_img").each(function(img){
        var image = new Image();
        image.src = $(this).attr("src");
        img[x++] = image.src; //this will increment x after the value x is used.
        console.log(img);
        console.log($(this).attr("src"));

好吧,当你认为你将声明的数组传递给匿名函数时 实际上,您使用以下代码定义了新的局部变量 img
.each(function(img){}) 只能在这个新的匿名函数中看到
因为这个函数是一个回调,应该有输入参数,将由 each() 函数传递:jQuery.each( array, callback )

现在你做了什么,你已经在函数范围内定义了你的数组img
$(window).on('load', function(){..});
然后再定义一个变量作为输入参数,将在这个函数范围内使用:
$(".gallery_img").each(function(img){..});
我猜你试图将这个变量传递给这个函数,但这是不必要的,因为你已经在更广泛的范围内声明了它并且这个变量已经在函数范围内可用。
Truth about javascript variable scopes

当您将此变量定义为回调函数参数时,您将获取新的局部变量 img,该变量获取匹配项的索引作为值,并且您的数组 img 在此函数中变得不可用。

所以你实际上必须做的是:

$(window).on('load', function(){
  var x = 0;
  var img = [];
    $(".gallery_img").each(function(ind, val){
      var image = new Image();
      image.src = $(this).attr("src");
      // Unnecessary, we already have index - ind, unless you use some filtering.
      // So you could get rid of x variable and use ind instead, like img[ind] = image.src
      x = x + 1; //<- x becomes 1
      img[x] = image.src; //<- img[0] is undefined as img[1] is where the index began.
      console.log(img);
      console.log($(this).attr("src"));

另外,我建议您习惯于 jsfiddle 设置您的示例代码,这将帮助您调试您的代码,我们也会帮助您处理实际示例。