-2

我正在尝试通过列表推导重写 CoffeeScript 中经典书籍“JavaScript:The Good Parts”中的示例:

var parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)
 (?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;

var url = “http://www.ora.com:80/goodparts?q#fragment”;
var result = parse_url.exec(url);
var names = ['url', 'scheme', 'slash', 'host', 'port', 'path', 'query', 'hash'];
var blanks = '       ';
var i;
for (i = 0; i < names.length; i += 1) {
     document.writeln(names[i] + ':' +
         blanks.substring(names[i].length), result[i]);
}

我不知道如何编写循环并坚持使用此代码:

console.log "#{name}: " for name in names
4

2 回答 2

3

我想你正在尝试做这样的事情

parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/

url = 'http://www.ora.com:80/goodparts?q#fragment'

result = parse_url.exec(url)

names = ['url', 'scheme', 'slash', 'host', 'port', 'path', 'query', 'hash']

alert "#{names[i]}: #{result[i]}" for i in [0..names.length-1]
于 2012-10-08T17:30:42.773 回答
1

如果有人来到这里实际上需要同时迭代两个数组,这可行:

for [course_event, remote_event] in zip(course.events, remote.events)
  course_event.lessons = remote_event.lessons if event.lessons_need_updating

zip()来自这里

zip = () ->
  lengthArray = (arr.length for arr in arguments)
  length = Math.min(lengthArray...)
  for i in [0...length]
    arr[i] for arr in arguments
于 2015-09-30T14:48:23.970 回答