最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is 'input.map' in google apps script (custom spreadsheet function) example? - Stack Overflow

programmeradmin3浏览0评论

I'm confused by this example from Google's Apps Script Guide. This function iterates over given range and performs a putation on each cell.

function DOUBLE(input) {

  if (input.map) {            // Test whether input is an array.
    return input.map(DOUBLE); // Recurse over array if so.
  } else {
    return input * 2;
  }

}

Things I don't understand:

  1. What object is the input in this function? typeof tells me it is a number, but shouldn't it be an array? It is after all a range of values (e.g. A2:B).
  2. What is the .map thing after the input variable? I cannot find it in the reference page. It is also not highlighted, as variables or functions are.
  3. The purpose of the conditional statement is unclear to me. Does return input.map(DOUBLE) mean "do whatever you find in the corresponding else statement over the whole array"? Why is it structured like so?

Any insights (or pointers to the right sources) much appreciated.

I'm confused by this example from Google's Apps Script Guide. This function iterates over given range and performs a putation on each cell.

function DOUBLE(input) {

  if (input.map) {            // Test whether input is an array.
    return input.map(DOUBLE); // Recurse over array if so.
  } else {
    return input * 2;
  }

}

Things I don't understand:

  1. What object is the input in this function? typeof tells me it is a number, but shouldn't it be an array? It is after all a range of values (e.g. A2:B).
  2. What is the .map thing after the input variable? I cannot find it in the reference page. It is also not highlighted, as variables or functions are.
  3. The purpose of the conditional statement is unclear to me. Does return input.map(DOUBLE) mean "do whatever you find in the corresponding else statement over the whole array"? Why is it structured like so?

Any insights (or pointers to the right sources) much appreciated.

Share Improve this question asked Dec 29, 2014 at 12:45 jakubjakub 5,1444 gold badges32 silver badges49 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

This code is an example of using introspection to conditionally execute the code. if (input.map) will return truthy if input is an Array (and has a map function) and will return falsy in all other cases.

This code is therefore testing to see whether input is an Array and if not, it is treating it as a number, otherwise it is treating it as an Array.

You can see the definition of the map function on MDN https://developer.mozilla/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Best book to learn about JavaScript is "JavaScript the Good Parts" http://www.amazon./JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/ref=sr_1_1?ie=UTF8&qid=1419857713&sr=8-1&keywords=javascript+the+good+parts

发布评论

评论列表(0)

  1. 暂无评论