ES6函数返回`undefined`而不是期望的字符串?

时间:2017-03-06 20:27:34

标签: javascript ecmascript-6 return each

我正在循环使用div来查找一系列div上的单个“活动”类。然后我想从该div获取数据属性。我正在获取数据属性,但似乎无法通过return将其传递出函数。它记录undefined

const getPostcardLink = () => {
  console.log('getPostcardLink()...');
  $('.postcard').each(function () {
    if ($(this).hasClass('active')) {
      const postcard = $(this).data('postcard');
      console.log(postcard);
      return postcard;
    }
    return 'error';
  });
};

const getStampLink = () => {
  console.log('getStampLink()...');
  $('.stamp').each(function () {
    if ($(this).hasClass('active')) {
      const stamp = $(this).data('stamp');
      console.log(stamp);
      return stamp;
    }
    return 'error';
  });
};

function updatePostcard() {
  const postcard = `images/_${getPostcardLink()}.jpg`;
  const stamp = `images/_${getStampLink()}.jpg`;
  console.log(`${postcard} with ${stamp}`);
}

$(document).ready(() => {
  updatePostcard();
});

日志返回...

getPostcardLink()...
p1
getStampLink()...
s1
images/_undefined.jpg with images/_undefined.jpg

1 个答案:

答案 0 :(得分:1)

public MainWindow() { DataContext = new ViewModel(); InitializeComponent(); }

使用.filter()和相同的模式
getStamp()