Join associative arrays in Javascript

和自甴很熟 提交于 2019-12-25 04:59:10

问题


I have two (or more) associative arrays in Javascript:

tagArray['title'] = ('<H1>title</H1>');
tagArray['text'] = ('<P>text</P>');

And want to join them like:

tagFinal = tagArray.join("<BR>");

But the result is empty.

It should result in: tagFinal = '<H1>title</H1><BR><P>text</P>';

What am I doing wrong? (I also tried without the tags, no difference) Or am I better off push()-ng it to a new array/string?


回答1:


There's no such thing as an "associative array" type in JavaScript. There are Objects and there are Arrays. The Array prototype has a .join() method, but Object does not.

(Objects in general do sort-of work like associative arrays, but there's no explicit functionality built in that mimics actual arrays. You can't find the "length" of an Object instance either, for example.)

You could write such a function however:

function smush( o, sep ) {
  var k, rv = null;
  for (k in o) {
    if (o.hasOwnProperty(k)) {
      if (rv !== null) rv += sep;
      rv += o[k];
    }
  }
  return rv;
}

Whether you'd really want to limit the "smush" function to working on direct properties of an object (as opposed to inherited ones), and whether you might want to filter by type, are things you'd have to decide for yourself.



来源:https://stackoverflow.com/questions/10980004/join-associative-arrays-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!