数组在Javascript中不起作用

时间:2016-06-01 21:11:12

标签: javascript

我尝试创建一个返回数组的函数,输出应为"我的名字是Sarah Adam"但实际上它并没有返回任何东西

type T() =
    interface seq<T> with
        member this.GetEnumerator() = ([] :> seq<T>).GetEnumerator()
        member this.GetEnumerator() = ([] :> seq<T>).GetEnumerator() :> System.Collections.IEnumerator

let z = new Something<string, T>()

5 个答案:

答案 0 :(得分:3)

你正在返回s(数组) - 我想你想要返回连接的消息。如:

已更新为包含变量姓氏

&#13;
&#13;
var m = 'My name is ';

function updateMsg(h, index) {
  "use strict";
  var el = m + h;

  // array of last names
  var s = ['Adam', 'Joseph'];

  return el + ' ' + s[index]; // return the concatenated string instead
}
var n1 = document.getElementById("msg");

n1.textContent = updateMsg("Sarah", 0); // invoke with param

// console log (confirmation)
console.log(updateMsg("Sarah", 0));
console.log(updateMsg("Meenah", 1));
&#13;
<div id="msg">
  hw
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

你可以使用currying来实现这一目标。只需将括号[0]换成括号(0)

&#13;
&#13;
var m = 'My name is ';

function updateMsg(h) {
  var s = ['Adam', 'Joseph'];
  return function(index) { // return a function that concatenates when given index
    return m + h + " " + s[index];
  };
}

var messageMaker = updateMsg("Sarah");
console.log(messageMaker(0));
console.log(messageMaker(1));
&#13;
&#13;
&#13;

答案 2 :(得分:1)

我认为您想要访问姓氏列表中的一个元素。我已经更正了您的代码,并执行了类似于您想要的操作:

&#13;
&#13;
let m = 'My name is ',
  s = ['Adam', 'Joseph'],
  updateMsg = (h, i) => m + h + ' ' + s[i],
  n1 = document.getElementById("msg");
n1.textContent = updateMsg("Sarah", 0);
&#13;
<p id="msg"></p>
&#13;
&#13;
&#13;

答案 3 :(得分:1)

详细信息在评论的来源中。

/*
Global variable: intro
*/
var intro = 'My name is ';

/*
Paramenter: who
*/
function updateMsg(who) {

  /* 
  Array of 2 Strings: guess 
  Named it guess because that's
  what I ended up doing with it
  */
  var guess = [' Shadey', ' Joseph'];

  /*
  Concated String: `hello`
  Since `intro` is global it's always accessible
  `who` is the parameter with value of "Slim"
  `guess[0]` = 'Shadey'
  */
  var hello = intro + who + guess[0];

  /*
  Output of `updateMsg()` function is `hello`
  which is "My name is Slim Shadey"
  */
  return hello;
}

/*
Reference the `output` element as `noLogic`
*/
var noLogic = document.getElementById("msg");

/*
Set `noLogic's` text to whatever `updateMsg()`
returns
`updateMsg()` parameter is "Slim"
*/
noLogic.textContent = updateMsg("Slim");
<output id="msg"></output>

答案 4 :(得分:0)

我想目的是返回el中每个名称前加s的数组。因此,您需要遍历数组以创建新数组。

var m = 'My name is ';
function updateMsg(h) {
  "use strict";
  var el = m + h;
  var s = ['Adam', 'Joseph'];
  return s.map(function(name) {
    return el + ' ' + name;
  });
}
var n1 = document.getElementById("msg");
n1.textContent = updateMsg("Sarah")[0];
<div id="msg">
</div>