我最近在代码中遇到了一个错误,这是由于我在 MDN 上查看 Map 对象详细信息时缺少“按插入顺序”文本。简而言之,我有一个地图对象,可以说
let myMap = new Map;
Run Code Online (Sandbox Code Playgroud)
然后,在填充它之后,我用一个简单的for .. of语句迭代它的内容。像这样
for (let [key, val] of myMap) {
...
}
Run Code Online (Sandbox Code Playgroud)
for循环中的代码依赖于 (key, value) 对按key排序。然而,填充地图的算法是以随机顺序执行的(我无法更改它)。为了解决这个问题,我现在首先将所有可能的键添加到地图对象中,如下所示:
let myMap = new Map;
for (let i=0; i<maxkey; ++i) myMap.set(key(i), undefined);
// And in the for loop
for (let [key, val] of myMap) {
if (typeof val === "undefined") continue;
//...
}
Run Code Online (Sandbox Code Playgroud)
幸运的是,它们的数量并不多(因此性能损失可以忽略不计),而且这是有效的。不过这个解决方案对我来说看起来有点尴尬。
还有更好的吗?
我正在尝试将我的代码更新为ES6,因为我使用的是Node 4.0,并且到目前为止它非常喜欢它的功能.但是我遇到了新的ES6 Map
数据结构的问题,因为它与用作密钥{}
时的行为不同Array
.我用它作为计数器图.
我运行此代码,我想知道如何使用数组作为键Map
.
"use strict";
var a = new Map();
a.set(['x','y'], 1);
console.log(a.get(['x','y']));
var b = {};
b[['x','y']] = 1;
console.log(b[['x','y']]);
Run Code Online (Sandbox Code Playgroud)
它打印出以下内容,第一行应该是,1
而不是undefined
:
undefined
1
Run Code Online (Sandbox Code Playgroud)
原始的JS映射将字符串化,我不想与新的ES6进行相同类型的stringify hack Map
.
如何将数组作为ES6的可靠键使用Map
?
我想使用 Map 而不是对象映射来声明一些键和值。但是 Typescript 似乎不支持 ES6 Map 的索引类型,这是正确的吗?有什么解决方法吗?
此外,我还希望使值类型安全,以便映射中的每个条目都具有与键对应的值的正确类型。
这是一些伪代码,描述了我想要实现的目标:
type Keys = 'key1' | 'key2';
type Values = {
'key1': string;
'key2': number;
}
/** Should display missing entry error */
const myMap = new Map<K in Keys, Values[K]>([
['key1', 'error missing key'],
]);
/** Should display wrong value type error for 'key2' */
const myMap = new Map<K in Keys, Values[K]>([
['key1', 'okay'],
['key2', 'error: this value should be number'],
]);
/** Should pass */
const myMap = …
Run Code Online (Sandbox Code Playgroud) typescript ecmascript-6 typescript-generics union-types es6-map
当我尝试这些代码时:
const map=new Map([['a', 1],['b', 2],['c', 3],['d', 4],['e', 5]]);
console.log(map.keys());
map.delete('a')
console.log(map.keys());
Run Code Online (Sandbox Code Playgroud)
chrome控制台将显示以下内容:
MapIterator {"a", "b", "c", "d", "e"}
MapIterator {"c", "d", "e"}
Run Code Online (Sandbox Code Playgroud)
"b"为什么不出现?
我知道如何分别做这两个事情,但是我确信必须有一种将它们组合在一起的方法。
我有一组类别,这些类别是从一组对象中提取的:
this.videoCategories = this.videos.map(v => v.category);
Run Code Online (Sandbox Code Playgroud)
但是,当然,此数组中有重复项。所以现在我做了
this.uniqueVideoCategories = this.videoCategories.filter((item, index) => {
return this.videoCategories.indexOf(item) === index;
});
Run Code Online (Sandbox Code Playgroud)
效果很好,我得到了一系列没有重复的类别。但是我试图通过将它们串在一起来学习和弄清代码,但这不起作用-产生空数组
constructor(private videoService: VideoService) {
this.videos = videoService.getVideos();
this.videoCategories = this.videos
.map(v => v.category)
.filter((item, index) => {
return this.videoCategories.indexOf(item) === index;
});
console.log(this.videoCategories);
}
Run Code Online (Sandbox Code Playgroud) 我最近将一些使用常规对象作为映射的代码转换为新的 es6Map
类。我很快就遇到了一个问题,虽然Map
该类包含一个forEach
like Array
,但它不包含一个some
方法以及许多其他Array.prototype
方法。
为了提供一些上下文,带有常规 JS 对象的原始代码如下所示:
var map = {
entry1: 'test',
entry2: 'test2'
};
Object.keys(map).some(key => {
var value = map[key];
// Do something...found a match
return true;
});
Run Code Online (Sandbox Code Playgroud)
的Map
类不包括一个entries
方法,但遗憾的是此返回一个Iterator
对象。这也不包括访问这些Array.prototype
方法的任何简单方法。
我很好奇是否有一种干净的方法可以做到这一点,或者我是否在咆哮错误的树。
我正在尝试在ES6中对此进行编码。以下是我要实现的目标。假设我有一个名为的对象数组schools
。
let schools = [
{name: 'YorkTown', country: 'Spain'},
{name: 'Stanford', country: 'USA'},
{name: 'Gymnasium Achern', country: 'Germany'}
];
Run Code Online (Sandbox Code Playgroud)
现在,我想编写一个函数editSchoolName
,该函数将带有3个参数schools
(这是我在上面定义的数组)oldName
和name
。
我将在参数中传递学校的名称,oldName
并且该名称应使用参数中的值进行更新name
。
我不想更改变量的状态,schools
因此我正在使用一个map
函数,该函数将返回具有更改的新数组。
该editSchoolName
函数将这样调用-
var updatedSchools = editSchoolName(schools, "YorkTown", "New Gen");
Run Code Online (Sandbox Code Playgroud)
在此,名称YorkTown
应替换为name New Gen
。因此,数组的期望值updatedSchools
应为-
let updatedSchools = [
{name: 'New Gen', country: 'Spain'},
{name: 'Stanford', country: 'USA'},
{name: 'Gymnasium Achern', country: 'Germany'}
];
Run Code Online (Sandbox Code Playgroud)
这就是我的editSchoolName函数的样子-
const editSchoolName …
Run Code Online (Sandbox Code Playgroud) 假设我有:
const m = new Map();
Run Code Online (Sandbox Code Playgroud)
两者之间是否存在性能差异:
for(let v of m){
}
Run Code Online (Sandbox Code Playgroud)
与
m.forEach(v => {});
Run Code Online (Sandbox Code Playgroud)
我假设Map.protoype.forEach
使用迭代器就像 for..of 一样?我在这里读到,在迭代期间使用 for..of 从映射中删除键是安全的,请参阅:ES6:在 Set/Map 迭代期间从 Set/Map 中删除元素是否危险?
我想知道用循环从地图中删除键是否安全Map.prototype.forEach
。
我正在制作一个社交媒体应用程序。我正在循环浏览所有评论并将其显示在用户界面上。当我单击编辑时,最后一条评论的文本总是显示在输入中。我尝试了很多不同的事情,改变了结构,使用bind来绑定上下文,但没有任何帮助。
我正在使用 React Material UI。
这是代码:
render() {
const { anchorEl } = this.state;
const open = Boolean(anchorEl);
return(
<Panel>
<form noValidate autoComplete="off" onSubmit={this.onSubmit}>
<TextField
id={`comment${this.state.post_id}`}
name="comment"
fullWidth
placeholder="Comment here"
margin="normal"
value={this.state.comment}
onChange={this.handleChange}
InputProps={{
endAdornment : <InputAdornment position="end">
<IconButton onClick={this.resetTextField}>
<CloseIcon/>
</IconButton>
</InputAdornment>
}}
/>
</form>
{this.props.comments && this.props.comments.length > 0 &&
<RenderComments
comments={this.state.comments}
open={open}
anchorEl={this.state.anchorEl}
handleClick={this.handleClick}
handleClose={this.handleClose}
handleDelete={this.handleDelete}
handleEdit={this.handleEdit}
/>
}
</Panel>
)
}
Run Code Online (Sandbox Code Playgroud)
const RenderComments = (props) => {
return props.comments.map(comment =>
<CommentBase
key={comment.id}
comment={comment}
open={props.open}
anchorEl={props.anchorEl}
handleClick={props.handleClick} …
Run Code Online (Sandbox Code Playgroud) I'm trying to write a method which will help me return an array of the object keys of all the currencies. But, I'm stuck at a point where I get the complete array of objects with key, value pair.
And yes, I primarily need to use ES6 methods. I wouldn't want to use any other iterators.
For e.g. : What I need:
['AED', 'ALL', 'AUD', 'EUR' .....]
Run Code Online (Sandbox Code Playgroud)
What I get :
[{AED: {"isDefault": true}}, {ALL: {"isDefault": true}}, {AUD: {"isDefault": true}}, …
Run Code Online (Sandbox Code Playgroud) es6-map ×10
javascript ×8
ecmascript-6 ×6
arrays ×5
dictionary ×2
node.js ×1
object ×1
reactjs ×1
typescript ×1
union-types ×1